package com.cygsunri.merchants.api;

import com.alibaba.fastjson.JSON;
import com.cygsunri.common.constant.DataName;
import com.cygsunri.common.constant.DevicePsrId;
import com.cygsunri.common.constant.DeviceType;
import com.cygsunri.common.entity.ConfigConstant;
import com.cygsunri.common.service.CommonDataService;
import com.cygsunri.consumption.entity.Branch;
import com.cygsunri.consumption.entity.Building;
import com.cygsunri.consumption.service.BranchService;
import com.cygsunri.consumption.service.BuildingService;
import com.cygsunri.income.service.IncomeCacheService;
import com.cygsunri.information.entity.Information;
import com.cygsunri.information.service.InformationService;
import com.cygsunri.measurement.entity.Flag;
import com.cygsunri.measurement.entity.MeasurementValue;
import com.cygsunri.scada.base.BasePSR;
import com.cygsunri.scada.service.ScadaPSRService;
import com.cygsunri.util.DateUtil;
import com.cygsunri.util.TimeUtil;
import com.github.abel533.echarts.Option;
import com.github.abel533.echarts.series.Bar;
import com.github.abel533.echarts.series.Line;
import net.sf.jsqlparser.expression.DateTimeLiteralExpression;
import org.assertj.core.util.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.io.UnsupportedEncodingException;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 首页api,目前代码都通过写死方式获取数据
 */
@RestController
@RequestMapping("/api/zhaoshang")
public class MerchantsController {

    @Autowired
    private CommonDataService commonDataService;

    @Autowired
    private InformationService informationService;

    @Autowired
    private BranchService branchService;

    @Autowired
    private BuildingService buildingService;

    @Autowired
    private ScadaPSRService scadaPSRService;

    @Autowired
    private IncomeCacheService incomeCacheService;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private ConfigConstant configConstant;

    @Value("${task.consumption.account.original}")
    private int original;

    /**
     * 多能协同-光伏api
     */
    @RequestMapping(value = "/home/solar/brief/substations/{id}", method = RequestMethod.GET)
    public ResponseEntity<List<MeasurementValue>> getSolarBrief(@PathVariable("id") String id) {
        List<MeasurementValue> list = Lists.newArrayList();
        MeasurementValue DayGenerated = commonDataService.getValue(id, DataName.DAY_GENERATED);
        MeasurementValue Efficiency = commonDataService.getValue(id, DataName.EFFICIENCY);
        MeasurementValue YearGenerated = commonDataService.getValue(id, DataName.YEAR_GENERATED);
        list.add(DayGenerated);
        list.add(Efficiency);

        int year = LocalDate.now().getYear();
        if (year == 2021) {
            YearGenerated .setData(commonDataService.getValue(id, DataName.TOTAL_GENERATED).getData()) ;
        }
        list.add(YearGenerated);
        return new ResponseEntity<>(list, HttpStatus.OK);
    }

    /**
     * 多能协同-储能api
     */
    @RequestMapping(value = "/home/ess/brief/substations/{id}", method = RequestMethod.GET)
    public ResponseEntity<List<MeasurementValue>> getEssBrief(@PathVariable("id") String id) throws UnsupportedEncodingException {
        List<MeasurementValue> list = Lists.newArrayList();
        MeasurementValue DayCharge = commonDataService.getValue(id, DataName.DAY_CHARGE);
        MeasurementValue YearCharge = commonDataService.getValue(id, DataName.YEAR_CHARGE);
        MeasurementValue SOC = commonDataService.getValue(id, DataName.SOC);
        MeasurementValue Efficiency = commonDataService.getValue(id, DataName.EFFICIENCY);
        MeasurementValue DayDischarge = commonDataService.getValue(id, DataName.DAY_DISCHARGE);
        MeasurementValue YearDischarge = commonDataService.getValue(id, DataName.YEAR_DISCHARGE);
        MeasurementValue efficiency = commonDataService.getValue(id, DataName.SOH);

        int year = LocalDate.now().getYear();
        if (year == 2021) {
            YearCharge .setData(commonDataService.getValue(id, DataName.TOTAL_CHARGE).getData()) ;
            YearDischarge .setData(commonDataService.getValue(id, DataName.TOTAL_DISCHARGE).getData()) ;
        }
        list.add(DayCharge);
        list.add(YearCharge);
        list.add(SOC);
        list.add(Efficiency);
        list.add(DayDischarge);
        list.add(YearDischarge);
        list.add(efficiency);
        return new ResponseEntity<>(list, HttpStatus.OK);
    }

    /**
     * 多能协同-风电api
     */
    @RequestMapping(value = "/home/wind/brief/substations/{id}", method = RequestMethod.GET)
    public ResponseEntity<List<MeasurementValue>> getWindBrief(@PathVariable("id") String id) {
        List<MeasurementValue> list = Lists.newArrayList();
        MeasurementValue DayGenerated = commonDataService.getValue(id, DataName.DAY_GENERATED);
        MeasurementValue Efficiency = commonDataService.getValue(id, DataName.EFFICIENCY);
        MeasurementValue YearGenerated = commonDataService.getValue(id, DataName.YEAR_GENERATED);
        list.add(DayGenerated);
        list.add(Efficiency);

        int year = LocalDate.now().getYear();
        if (year == 2021) {
            YearGenerated .setData(commonDataService.getValue(id, DataName.TOTAL_GENERATED).getData()) ;
        }
        list.add(YearGenerated);
        return new ResponseEntity<>(list, HttpStatus.OK);
    }

    /**
     * 概况api
     */
    @RequestMapping(value = "/home/overview", method = RequestMethod.GET)
    public ResponseEntity<List<MeasurementValue>> getOverview() {
        List<MeasurementValue> list = Lists.newArrayList();

        MeasurementValue solar = commonDataService.getValue(DevicePsrId.SOLAR, DataName.YEAR_GENERATED);
        MeasurementValue wind = commonDataService.getValue(DevicePsrId.WIND, DataName.YEAR_GENERATED);

        int year = LocalDate.now().getYear();
        if (year == 2021) {
            solar .setData(commonDataService.getValue(DevicePsrId.SOLAR, DataName.TOTAL_GENERATED).getData()) ;
            wind .setData(commonDataService.getValue(DevicePsrId.WIND, DataName.TOTAL_GENERATED).getData()) ;
        }
        Double cleanEnergyData = (solar.isInValid() ? 0d : solar.getData()) + (wind.isInValid() ? 0d : wind.getData());
        MeasurementValue cleanEnergy = new MeasurementValue().setComments("年清洁能源").setData(cleanEnergyData).setQuality(MeasurementValue.Quality.Normal);
        list.add(cleanEnergy);

        List<Branch> officeElectricityBranches = branchService.getBranchesByEnergyItem("OfficeElectricity");
        Double officeElectricityV = commonDataService.getSumOfBranches(officeElectricityBranches, DataName.ELECTRICITY);

        MeasurementValue consumption = commonDataService.getValue(DevicePsrId.CONSUMPTION, DataName.ELECTRICITY,DateUtil.nowMilliSeconds(), Flag.YEAR_DIFF);
        Double totalUse = (consumption.isInValid() ? 0d : consumption.getData());
        MeasurementValue total = new MeasurementValue().setComments("年办公楼用电").setData(totalUse).setQuality(MeasurementValue.Quality.Normal);
        if (year == 2021) {
            total.setData(officeElectricityV);
        }
        list.add(total);

//        MeasurementValue total = commonDataService.getValue(DevicePsrId.CONSUMPTION, DataName.YEAR_ELECTRICITY);
//        if (total.isInValid()) {
//            //园区总能耗=光伏发电量+风电发电量+#1~5层及机房电表总有功之和
////            MeasurementValue meter1E = commonDataService.getValue("Czdb1", DataName.ELECTRICITY);
////            MeasurementValue meter1RE = commonDataService.getValue("Czdb1", DataName.REVERSE_ELECTRICITY);
////            Double meter1 = meter1E.isInValid() ? 0d : (meter1E.getData() - (meter1RE.isInValid() ? 0d : meter1RE.getData()));
////            MeasurementValue meter2E = commonDataService.getValue("Czdb2", DataName.ELECTRICITY);
////            MeasurementValue meter2RE = commonDataService.getValue("Czdb2", DataName.REVERSE_ELECTRICITY);
////            Double meter2 = meter2E.isInValid() ? 0d : (meter2E.getData() - (meter2RE.isInValid() ? 0d : meter2RE.getData()));
//            MeasurementValue meter1 = commonDataService.getValue("CONE1l", DataName.ELECTRICITY);
//            MeasurementValue meter2 = commonDataService.getValue("CONE2l", DataName.ELECTRICITY);
//            MeasurementValue meter3 = commonDataService.getValue("CONE3l", DataName.ELECTRICITY);
//            MeasurementValue meter4 = commonDataService.getValue("CONE4l", DataName.ELECTRICITY);
//            MeasurementValue meter5 = commonDataService.getValue("CONE5l", DataName.ELECTRICITY);
//            MeasurementValue meterJF = commonDataService.getValue("CONEjf", DataName.ELECTRICITY);
//            Double meter = (meter1.isInValid() ? 0d : meter1.getData()) + (meter2.isInValid() ? 0d : meter2.getData()) + (meter3.isInValid() ? 0d : meter3.getData())
//                    + (meter4.isInValid() ? 0d : meter4.getData()) + (meter5.isInValid() ? 0d : meter5.getData()) + (meterJF.isInValid() ? 0d : meterJF.getData());
//            Double totalUse = cleanEnergy.getData() + meter - original;
//            total = new MeasurementValue().setComments("累计办公楼用电").setData(totalUse).setQuality(MeasurementValue.Quality.Normal);
//        }

        double savingCoalData = (solar.isInValid() ? 0d : solar.getData() * 0.000326) + (wind.isInValid() ? 0d : wind.getData() * 0.000326);
        MeasurementValue savingCoal = new MeasurementValue().setComments("节约标准煤").setData(savingCoalData).setQuality(MeasurementValue.Quality.Normal);
        list.add(savingCoal);

        double reduceCarbonData = (solar.isInValid() ? 0d : solar.getData() * 0.000997)+(wind.isInValid() ? 0d : wind.getData() * 0.000997);
        MeasurementValue reduceCarbon = new MeasurementValue().setComments("减少二氧化碳").setData(reduceCarbonData).setQuality(MeasurementValue.Quality.Normal);
        list.add(reduceCarbon);

        //经济效益=光伏+风电+充电桩
        Double incomeTotal = 0d;
        List<BasePSR> inverters = scadaPSRService.getDevicesByType(DeviceType.INVERTER.getKey());
        for (BasePSR inverter : inverters) {
            Double income = incomeCacheService.getIncomeSum(inverter.getId(), DataName.TOTAL_GENERATED, 6, "common");
            incomeTotal += income == null ? 0d : income;
        }

        List<BasePSR> pcsList = scadaPSRService.getDevicesByType(DeviceType.PCS.getKey());
        for (BasePSR pcs : pcsList) {
            Double charge = incomeCacheService.getIncomeSum(pcs.getId(), DataName.TOTAL_CHARGE, 6, "common");
            Double discharge = incomeCacheService.getIncomeSum(pcs.getId(), DataName.TOTAL_DISCHARGE, 7, "common");
            incomeTotal += ((charge == null || discharge == null) ? 0d : (discharge - charge));
        }

        List<BasePSR> dc_charges = scadaPSRService.getDevicesByType(DeviceType.DC_CHARGING.getKey());
        for (BasePSR dc_charge : dc_charges) {
            Double common1 = incomeCacheService.getIncomeSum(dc_charge.getId(), DataName.GUN1_TOTAL_CHARGE, 6, "common");
            Double charge1 = incomeCacheService.getIncomeSum(dc_charge.getId(), DataName.GUN1_TOTAL_CHARGE, 6, "dcCharge");
            incomeTotal += ((common1 == null || charge1 == null) ? 0d : (charge1 - common1));

            Double common2 = incomeCacheService.getIncomeSum(dc_charge.getId(), DataName.GUN2_TOTAL_CHARGE, 6, "common");
            Double charge2 = incomeCacheService.getIncomeSum(dc_charge.getId(), DataName.GUN2_TOTAL_CHARGE, 6, "dcCharge");
            incomeTotal += ((common2 == null || charge2 == null) ? 0d : (charge2 - common2));
        }

        List<BasePSR> ac_charges = scadaPSRService.getDevicesByType(DeviceType.AC_CHARGING.getKey());
        for (BasePSR ac_charge : ac_charges) {
            Double common1 = incomeCacheService.getIncomeSum(ac_charge.getId(), DataName.GUN1_TOTAL_CHARGE, 6, "common");
            Double charge1 = incomeCacheService.getIncomeSum(ac_charge.getId(), DataName.GUN1_TOTAL_CHARGE, 6, "acCharge");
            incomeTotal += ((common1 == null || charge1 == null) ? 0d : (charge1 - common1));
        }
        MeasurementValue economicBenefit = new MeasurementValue().setComments("经济效益").setData(incomeTotal).setQuality(MeasurementValue.Quality.Normal);
        list.add(economicBenefit);

        Information information = informationService.getInformationByPsrID("Jidian");
        int days;
        if (information == null || information.getConnectTime() == null) {
            days = DateUtil.getDaysFromToday("2020-01-01");
        } else {
            days = DateUtil.getDaysFromToday(information.getConnectTime());
        }
        MeasurementValue runningDays = new MeasurementValue().setComments("安全运行天数").setData(days * 1d).setQuality(MeasurementValue.Quality.Normal);
        list.add(runningDays);
        return new ResponseEntity<>(list, HttpStatus.OK);
    }

    /**
     * 中间图表api
     */
    @RequestMapping(value = "/home/center/center", method = RequestMethod.GET)
    public ResponseEntity<List<MeasurementValue>> getCenter() {
        List<MeasurementValue> list = Lists.newArrayList();

//        MeasurementValue solarTotal = commonDataService.getValue(DevicePsrId.SOLAR, DataName.TOTAL_GENERATED);
//        list.add(solarTotal);
        MeasurementValue solar = commonDataService.getValue(DevicePsrId.SOLAR, DataName.YEAR_GENERATED);
        MeasurementValue wind = commonDataService.getValue(DevicePsrId.WIND, DataName.YEAR_GENERATED);

        int year = LocalDate.now().getYear();
        if (year == 2021) {
            solar .setData(commonDataService.getValue(DevicePsrId.SOLAR, DataName.TOTAL_GENERATED).getData()) ;
            wind .setData(commonDataService.getValue(DevicePsrId.WIND, DataName.TOTAL_GENERATED).getData()) ;
        }
        Double cleanEnergyData = (solar.isInValid() ? 0d : solar.getData()) + (wind.isInValid() ? 0d : wind.getData());
        MeasurementValue cleanEnergy = new MeasurementValue().setComments("年清洁能源").setData(cleanEnergyData).setQuality(MeasurementValue.Quality.Normal);
        list.add(cleanEnergy);

        MeasurementValue essDischarge = commonDataService.getValue(DevicePsrId.ESS, DataName.YEAR_DISCHARGE);
        if (year == 2021) {
            essDischarge .setData(commonDataService.getValue(DevicePsrId.ESS, DataName.TOTAL_DISCHARGE).getData()) ;
        }
        Double yearDischarge = (essDischarge.isInValid() ? 0d : essDischarge.getData());
        MeasurementValue yearDischargeEss = new MeasurementValue().setComments("储能年放电量").setData(yearDischarge).setQuality(MeasurementValue.Quality.Normal);
        list.add(yearDischargeEss);

        MeasurementValue essCharge = commonDataService.getValue(DevicePsrId.ESS, DataName.YEAR_CHARGE);
        if (year == 2021) {
            essCharge .setData(commonDataService.getValue(DevicePsrId.ESS, DataName.TOTAL_CHARGE).getData()) ;
        }
        Double yearCharge = (essCharge.isInValid() ? 0d : essCharge.getData());
        MeasurementValue yearChargeEss = new MeasurementValue().setComments("储能年充电量").setData(yearCharge).setQuality(MeasurementValue.Quality.Normal);
        list.add(yearChargeEss);

        List<Branch> officeElectricityBranches = branchService.getBranchesByEnergyItem("OfficeElectricity");
        Double officeElectricityV = commonDataService.getSumOfBranches(officeElectricityBranches, DataName.ELECTRICITY);

        MeasurementValue consumption = commonDataService.getValue(DevicePsrId.CONSUMPTION, DataName.ELECTRICITY, DateUtil.nowMilliSeconds(), Flag.YEAR_DIFF);
        Double totalUse = (consumption.isInValid() ? 0d : consumption.getData());
        MeasurementValue officeYearElectricity = new MeasurementValue().setComments("办公楼").setData(totalUse).setQuality(MeasurementValue.Quality.Normal);
        if (year == 2021) {
            officeYearElectricity.setData(officeElectricityV);
        }
        list.add(officeYearElectricity);
//        MeasurementValue meter1 = commonDataService.getValue("CONE1l", DataName.ELECTRICITY);
//        MeasurementValue meter2 = commonDataService.getValue("CONE2l", DataName.ELECTRICITY);
//        MeasurementValue meter3 = commonDataService.getValue("CONE3l", DataName.ELECTRICITY);
//        MeasurementValue meter4 = commonDataService.getValue("CONE4l", DataName.ELECTRICITY);
//        MeasurementValue meter5 = commonDataService.getValue("CONE5l", DataName.ELECTRICITY);
//        MeasurementValue meterJF = commonDataService.getValue("CONEjf", DataName.ELECTRICITY);
//        Double meter = (meter1.isInValid() ? 0d : meter1.getData()) + (meter2.isInValid() ? 0d : meter2.getData()) + (meter3.isInValid() ? 0d : meter3.getData())
//                + (meter4.isInValid() ? 0d : meter4.getData()) + (meter5.isInValid() ? 0d : meter5.getData()) + (meterJF.isInValid() ? 0d : meterJF.getData());
//        Double totalUse = meter - original;
//        MeasurementValue total = new MeasurementValue().setComments("市电").setData(totalUse).setQuality(MeasurementValue.Quality.Normal);
//        list.add(total);

//        MeasurementValue essDischarge = commonDataService.getValue(DevicePsrId.ESS, DataName.TOTAL_DISCHARGE);
//        list.add(essDischarge);
//        MeasurementValue essCharge = commonDataService.getValue(DevicePsrId.ESS, DataName.TOTAL_CHARGE);
//        list.add(essCharge);
//        MeasurementValue meter1E = commonDataService.getValue("Czdb1", DataName.ELECTRICITY);
//        MeasurementValue meter1RE = commonDataService.getValue("Czdb1", DataName.REVERSE_ELECTRICITY);
//        MeasurementValue meter2E = commonDataService.getValue("Czdb2", DataName.ELECTRICITY);
//        MeasurementValue meter2RE = commonDataService.getValue("Czdb2", DataName.REVERSE_ELECTRICITY);
//        Double reverse = (meter1RE.isInValid() ? 0d : meter1RE.getData()) + (meter2RE.isInValid() ? 0d : meter2RE.getData());
//        MeasurementValue meterDischarge = new MeasurementValue().setComments("市电反向").setData(reverse).setQuality(MeasurementValue.Quality.Normal);
//        list.add(meterDischarge);
//
//        Double forward = (meter1E.isInValid() ? 0d : meter1E.getData()) + (meter2E.isInValid() ? 0d : meter2E.getData()) - original;
//        MeasurementValue meterCharge = new MeasurementValue().setComments("市电正向").setData(forward).setQuality(MeasurementValue.Quality.Normal);
//        list.add(meterCharge);

        MeasurementValue officeElectricity = new MeasurementValue().setComments("办公楼累计用电量").setData(officeElectricityV).setQuality(MeasurementValue.Quality.Normal);
        list.add(officeElectricity);

        MeasurementValue chargePie = commonDataService.getValue(DevicePsrId.CHARGE, DataName.TOTAL_CHARGE);
        list.add(chargePie);

        List<Branch> officeWaterBranches = branchService.getBranchesByEnergyItem("OfficeWater");
        Double officeWaterV = commonDataService.getSumOfBranches(officeWaterBranches, DataName.WATER);
        MeasurementValue officeWater = new MeasurementValue().setComments("办公楼累计用水量").setData(officeWaterV).setQuality(MeasurementValue.Quality.Normal);
        list.add(officeWater);

//        List<Branch> dynamicBranches = branchService.getBranchesByEnergyItem("Dynamic");
//        Double dynamicV = commonDataService.getSumOfBranches(dynamicBranches, DataName.ELECTRICITY);
//        MeasurementValue dynamic = new MeasurementValue().setComments("食堂").setData(dynamicV).setQuality(MeasurementValue.Quality.Normal);
//        list.add(dynamic);

        return new ResponseEntity<>(list, HttpStatus.OK);
    }

    /**
     * 水球图api
     */
    @RequestMapping(value = "/home/center/charts", method = RequestMethod.GET)
    public ResponseEntity<List<Double>> getCenterCharts() {
        List<Double> list = Lists.newArrayList();

        MeasurementValue solar = commonDataService.getValue(DevicePsrId.SOLAR, DataName.EFFICIENCY);
        list.add(solar.isInValid() ? Double.NaN : solar.getData());

        MeasurementValue SOC = commonDataService.getValue(DevicePsrId.ESS, DataName.SOC);
        list.add(SOC.isInValid() ? Double.NaN : SOC.getData());

        MeasurementValue air = commonDataService.getValue(DevicePsrId.AIR, DataName.UTILIZATION);
        list.add(air.isInValid() ? Double.NaN : air.getData());

        MeasurementValue charge = commonDataService.getValue(DevicePsrId.CHARGE, DataName.UTILIZATION);
        list.add(charge.isInValid() ? Double.NaN : charge.getData());

        return new ResponseEntity<>(list, HttpStatus.OK);
    }

    /**
     * 有序充电api
     */
    @RequestMapping(value = "/home/OrderCharge", method = RequestMethod.GET)
    public ResponseEntity<List<MeasurementValue>> getOrderCharge() {
        List<MeasurementValue> list = Lists.newArrayList();

        MeasurementValue charge = commonDataService.getValue(DevicePsrId.CHARGE, DataName.YEAR_CHARGE);
        MeasurementValue ess = commonDataService.getValue(DevicePsrId.ESS, DataName.YEAR_CHARGE);
        int year = LocalDate.now().getYear();
        if (year == 2021) {
            charge .setData(commonDataService.getValue(DevicePsrId.CHARGE, DataName.TOTAL_CHARGE).getData()) ;
            ess .setData(commonDataService.getValue(DevicePsrId.ESS, DataName.TOTAL_CHARGE).getData()) ;
        }
        Double yearChargeData = (charge.isInValid() ? 0d : charge.getData()) + (ess.isInValid() ? 0d : ess.getData());
        MeasurementValue yearCharge = new MeasurementValue().setComments("年已充电量").setData(yearChargeData).setQuality(MeasurementValue.Quality.Normal);
        list.add(yearCharge);
        return new ResponseEntity<>(list, HttpStatus.OK);
//        return new ResponseEntity<>(commonDataService.getValue(DevicePsrId.CHARGE, DataName.YEAR_CHARGE), HttpStatus.OK);
    }

    /**
     * 有序充电饼图api
     */
    @RequestMapping(value = "/home/OrderCharge/charts", method = RequestMethod.GET)
    public ResponseEntity<List<Double>> getOrderChargeCharts() {
        List<Double> list = Lists.newArrayList();
        MeasurementValue charge = commonDataService.getValue(DevicePsrId.CHARGE, DataName.YEAR_CHARGE);
        MeasurementValue ess = commonDataService.getValue(DevicePsrId.ESS, DataName.YEAR_CHARGE);
        int year = LocalDate.now().getYear();
        if (year == 2021) {
            charge .setData(commonDataService.getValue(DevicePsrId.CHARGE, DataName.TOTAL_CHARGE).getData()) ;
            ess .setData(commonDataService.getValue(DevicePsrId.ESS, DataName.TOTAL_CHARGE).getData()) ;
        }
        list.add(charge.isInValid() ? Double.NaN : charge.getData());
        list.add(ess.isInValid() ? Double.NaN : ess.getData());

//        MeasurementValue gateway = new MeasurementValue().setQuality(MeasurementValue.Quality.Invalid);//commonDataService.getValue("Obwgbwb", DataName.TOTAL_CHARGE);
//        list.add(charge.isInValid() ? Double.NaN : charge.getData());
//        list.add(charge.isInValid() || gateway.isInValid() ? Double.NaN : gateway.getData() - charge.getData());
        return new ResponseEntity<>(list, HttpStatus.OK);
    }

    /**
     * 功率监测api
     */
    @RequestMapping(value = "/home/DemandResponse/charts", method = RequestMethod.GET)
    public ResponseEntity<List<Map<String, Object>>> getDemandResponseCharts() {
        List<Map<String, Object>> mapList = Lists.newArrayList();
        //并网开关暂时写死
//        MeasurementValue gateWay = commonDataService.getValue("Kbwzkg1k", DataName.OUT_POWER);
//        mapList.add(new HashMap<String, Object>() {{
//            put("name", gateWay.getO().getName());
//            put("value", gateWay.isInValid() ? "-" : gateWay.getData());
//        }});

        //功率name都是OUT_POWER的设备一起遍历
        List<BasePSR> basePSRList = scadaPSRService.getDevicesByType(DeviceType.INVERTER.getKey());
        basePSRList.addAll(scadaPSRService.getDevicesByType(DeviceType.PCS.getKey()));
        for (BasePSR basePSR : basePSRList) {
            MeasurementValue m = commonDataService.getValue(basePSR.getId(), DataName.OUT_POWER);

            mapList.add(new HashMap<String, Object>() {{
                put("name", m.getO().getName());
                put("value", m.isInValid() ? "-" : m.getData());
            }});

        }

        List<BasePSR> ac_charges = scadaPSRService.getDevicesByType(DeviceType.AC_CHARGING.getKey());
        for (BasePSR basePSR : ac_charges) {
            //交流桩只有一个枪
            MeasurementValue m = commonDataService.getValue(basePSR.getId(), DataName.GUN1_OUT_POWER);
            mapList.add(new HashMap<String, Object>() {{
                put("name", m.getO().getName());
                put("value", m.isInValid() ? "-" : m.getData());
            }});
        }

        List<BasePSR> dc_charges = scadaPSRService.getDevicesByType(DeviceType.DC_CHARGING.getKey());
        for (BasePSR basePSR : dc_charges) {
            MeasurementValue gun1 = commonDataService.getValue(basePSR.getId(), DataName.GUN1_OUT_POWER);
            Double v = 0d;
            String name = basePSR.getName();
            if (!gun1.isInValid()) {
                v += gun1.getData();
            }
            MeasurementValue gun2 = commonDataService.getValue(basePSR.getId(), DataName.GUN2_OUT_POWER);
            if (!gun2.isInValid()) {
                v += gun2.getData();
            }
            Double finalV = v;
            mapList.add(new HashMap<String, Object>() {{
                put("name", name);
                put("value", finalV);
            }});
        }

        return new ResponseEntity<>(mapList, HttpStatus.OK);
    }

    /**
     * 能量监测-办公能耗api
     * 当日能量监测
     */
    @RequestMapping(value = "/home/OfficeEnergy/charts", method = RequestMethod.GET)
    public ResponseEntity<List<List<Object>>> getOfficeEnergyCharts() {
        List<List<Object>> list = Lists.newArrayList();
        List<Object> list1 = Lists.newArrayList();

        MeasurementValue solar = commonDataService.getValue(DevicePsrId.SOLAR, DataName.TOTAL_GENERATED,DateUtil.nowMilliSeconds(), Flag.DAY_DIFF);
        MeasurementValue wind = commonDataService.getValue(DevicePsrId.WIND, DataName.TOTAL_GENERATED,DateUtil.nowMilliSeconds(), Flag.DAY_DIFF);
        MeasurementValue electricity = commonDataService.getValue(DevicePsrId.CONSUMPTION, DataName.ELECTRICITY, DateUtil.nowMilliSeconds(), Flag.DAY_DIFF);
        list1.add(electricity.isInValid() ? Double.NaN : electricity.getData());
        list1.add("");
        list1.add((solar.isInValid() ? 0d : solar.getData()) + (wind.isInValid() ? 0d : wind.getData()));

        List<Object> list2 = Lists.newArrayList();
        list2.add("");
        MeasurementValue water = commonDataService.getValue(DevicePsrId.CONSUMPTION, DataName.WATER, DateUtil.nowMilliSeconds(), Flag.DAY_DIFF);
        list2.add(water.isInValid() ? Double.NaN : water.getData());
        list2.add("");

        list.add(list1);
        list.add(list2);
//        List<Building> buildings = buildingService.getAllBuilding();
//        String[] energySorts = {DataName.ELECTRICITY, DataName.WATER};
//        for (String energySort : energySorts) {
//            MeasurementValue total = commonDataService.getValue(DevicePsrId.CONSUMPTION, energySort, DateUtil.nowMilliSeconds(), Flag.DAY_DIFF);
//            List<Double> doubles = Lists.newArrayList();
//            Double sum = 0d;
//            for (Building building : buildings) {
//                MeasurementValue m = commonDataService.getValue(building.getPsrID(), energySort, DateUtil.nowMilliSeconds(), Flag.DAY_DIFF);
//                if (m.isInValid()) {
//                    doubles.add(Double.NaN);
//                } else {
//                    doubles.add(m.getData());
//                    sum += m.getData();
//                }
//            }
//            doubles.add(total.isInValid() ? Double.NaN : total.getData() - sum);
//            list.add(doubles);
//        }
        return new ResponseEntity<>(list, HttpStatus.OK);
    }

    /**
     * 能量监测-空调api
     */
    @RequestMapping(value = "/home/EnergyTemperatureHumidity/charts", method = RequestMethod.GET)
    public ResponseEntity<String> getEnergyTemperature() {
        Option option = new Option();
        List<Branch> airBranches = branchService.getBranchesByEnergyItem("OfficeElectricity");
        List<String> times = DateUtil.getHours(DateUtil.today());
        times.remove(0);
        for (Branch branch : airBranches) {
            Bar bar = new Bar(branch.getName());
            option.series(bar);
            for (String time : times) {
                MeasurementValue m = commonDataService.getValue(branch.getPsrID(), DataName.ELECTRICITY, TimeUtil.toMilliSeconds(time), Flag.HOUR_DIFF);
                bar.data(m.isInValid() ? "-" : m.getData());
            }
        }

        Line line = new Line("内机温度");
        option.series(line);
        List<MeasurementValue> values = commonDataService.getHistoryValue(DevicePsrId.AIR, DataName.TEMPERATURE, DateUtil.startOfToday(), DateUtil.endOfToday(), 60, 2, false);
        for (MeasurementValue m : values) {
            line.data(m.isInValid() ? "-" : m.getData());
        }
        return new ResponseEntity<>(JSON.toJSONString(option), HttpStatus.OK);
    }

    /**
     * 电力情况对比（用电）-储能/充电桩/办公楼api
     */
    @RequestMapping(value = "/home/consumption/charts", method = RequestMethod.GET)
    public ResponseEntity<List<Double>> getConsumptionCharts() {
        List<Double> list = Lists.newArrayList();
        MeasurementValue ess = commonDataService.getValue(DevicePsrId.ESS, DataName.YEAR_CHARGE);
        MeasurementValue charge = commonDataService.getValue(DevicePsrId.CHARGE, DataName.YEAR_CHARGE);
//        MeasurementValue officeBuilding = commonDataService.getValue(DevicePsrId.CONSUMPTION, DataName.YEAR_ELECTRICITY);
        MeasurementValue officeBuilding = commonDataService.getValue(DevicePsrId.CONSUMPTION, DataName.ELECTRICITY, DateUtil.nowMilliSeconds(), Flag.YEAR_DIFF);

        int year = LocalDate.now().getYear();
        if (year == 2021) {
            ess .setData(commonDataService.getValue(DevicePsrId.ESS, DataName.TOTAL_CHARGE).getData()) ;
            charge .setData(commonDataService.getValue(DevicePsrId.CHARGE, DataName.TOTAL_CHARGE).getData()) ;
            officeBuilding .setData(commonDataService.getValue(DevicePsrId.CONSUMPTION, DataName.ELECTRICITY).getData());
        }
        list.add(ess.isInValid() ? Double.NaN : ess.getData());
        list.add(charge.isInValid() ? Double.NaN : charge.getData());
        list.add(officeBuilding.isInValid() ? Double.NaN : officeBuilding.getData());

//        MeasurementValue solar = commonDataService.getValue(DevicePsrId.SOLAR, DataName.TOTAL_GENERATED);
//        MeasurementValue wind = commonDataService.getValue(DevicePsrId.WIND, DataName.TOTAL_GENERATED);
//        Double cleanEnergy = (solar.isInValid() ? 0d : solar.getData()) + (wind.isInValid() ? 0d : wind.getData());
//        list.add(cleanEnergy);
//        MeasurementValue meter1 = commonDataService.getValue("CONE1l", DataName.ELECTRICITY);
//        MeasurementValue meter2 = commonDataService.getValue("CONE2l", DataName.ELECTRICITY);
//        MeasurementValue meter3 = commonDataService.getValue("CONE3l", DataName.ELECTRICITY);
//        MeasurementValue meter4 = commonDataService.getValue("CONE4l", DataName.ELECTRICITY);
//        MeasurementValue meter5 = commonDataService.getValue("CONE5l", DataName.ELECTRICITY);
//        MeasurementValue meterJF = commonDataService.getValue("CONEjf", DataName.ELECTRICITY);
//        Double officeBuiling = (meter1.isInValid() ? 0d : meter1.getData()) + (meter2.isInValid() ? 0d : meter2.getData()) + (meter3.isInValid() ? 0d : meter3.getData())
//                + (meter4.isInValid() ? 0d : meter4.getData()) + (meter5.isInValid() ? 0d : meter5.getData()) + (meterJF.isInValid() ? 0d : meterJF.getData());
//        Double totalUse = officeBuiling - original;
//        list.add(totalUse);

//        List<Branch> lightBranches = branchService.getBranchesByEnergyItem("Lighting");
//        Double lightingV = commonDataService.getSumOfBranches(lightBranches, DataName.ELECTRICITY);
//        list.add(lightingV);
//
//        List<Branch> airBranches = branchService.getBranchesByEnergyItem("Air");
//        Double airV = commonDataService.getSumOfBranches(airBranches, DataName.ELECTRICITY);
//        list.add(airV);
//
//        List<Branch> dynamicBranches = branchService.getBranchesByEnergyItem("Dynamic");
//        Double dynamicV = commonDataService.getSumOfBranches(dynamicBranches, DataName.ELECTRICITY);
//        list.add(dynamicV);

//        MeasurementValue total = commonDataService.getValue(DevicePsrId.CONSUMPTION, DataName.ELECTRICITY);
//        list.add(total.isInValid() ? Double.NaN : (total.getData() - (officeBuiling.isInValid() ? 0d : officeBuiling.getData()) - (charge.isInValid() ? 0d : charge.getData())));
        return new ResponseEntity<>(list, HttpStatus.OK);
    }

    /**
     * 电力情况对比（发电）-风电/光伏/储能api
     */
    @RequestMapping(value = "/home/CleanEnergy/charts", method = RequestMethod.GET)
    public ResponseEntity<List<Double>> getCleanEnergyCharts() {
        List<Double> list = Lists.newArrayList();
        MeasurementValue wind = commonDataService.getValue(DevicePsrId.WIND, DataName.YEAR_GENERATED);
        MeasurementValue solar = commonDataService.getValue(DevicePsrId.SOLAR, DataName.YEAR_GENERATED);
        MeasurementValue ess = commonDataService.getValue(DevicePsrId.ESS, DataName.YEAR_DISCHARGE);
//        MeasurementValue meter1 = commonDataService.getValue("Czdb1", DataName.ELECTRICITY, DateUtil.nowMilliSeconds(), Flag.DAY_DIFF);
//        MeasurementValue meter2 = commonDataService.getValue("Czdb2", DataName.ELECTRICITY, DateUtil.nowMilliSeconds(), Flag.DAY_DIFF);
//        MeasurementValue meter1 = commonDataService.getValue("CONE1l",DataName.ELECTRICITY, DateUtil.nowMilliSeconds(), Flag.DAY_DIFF);
//        MeasurementValue meter2 = commonDataService.getValue("CONE2l", DataName.ELECTRICITY, DateUtil.nowMilliSeconds(), Flag.DAY_DIFF);
//        MeasurementValue meter3 = commonDataService.getValue("CONE3l", DataName.ELECTRICITY, DateUtil.nowMilliSeconds(), Flag.DAY_DIFF);
//        MeasurementValue meter4 = commonDataService.getValue("CONE4l",DataName.ELECTRICITY, DateUtil.nowMilliSeconds(), Flag.DAY_DIFF);
//        MeasurementValue meter5 = commonDataService.getValue("CONE5l", DataName.ELECTRICITY, DateUtil.nowMilliSeconds(), Flag.DAY_DIFF);
//        MeasurementValue meterJF = commonDataService.getValue("CONEjf", DataName.ELECTRICITY, DateUtil.nowMilliSeconds(), Flag.DAY_DIFF);
//        Double meter = (meter1.isInValid() ? 0d : meter1.getData()) + (meter2.isInValid() ? 0d : meter2.getData()) + (meter3.isInValid() ? 0d : meter3.getData())
//                + (meter4.isInValid() ? 0d : meter4.getData()) + (meter5.isInValid() ? 0d : meter5.getData()) + (meterJF.isInValid() ? 0d : meterJF.getData());
        int year = LocalDate.now().getYear();
        if (year == 2021) {
            wind .setData(commonDataService.getValue(DevicePsrId.WIND, DataName.TOTAL_GENERATED).getData()) ;
            solar .setData(commonDataService.getValue(DevicePsrId.SOLAR, DataName.TOTAL_GENERATED).getData()) ;
            ess .setData(commonDataService.getValue(DevicePsrId.ESS, DataName.TOTAL_DISCHARGE).getData());
        }
        list.add(wind.isInValid() ? Double.NaN : wind.getData());
        list.add(solar.isInValid() ? Double.NaN : solar.getData());
        list.add(ess.isInValid() ? Double.NaN : ess.getData());
//        list.add(meter);
        return new ResponseEntity<>(list, HttpStatus.OK);
    }
}
